package org.itboys.mobile.controller.weixin;

import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.commons.CommonConstants;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mobile.dto.SundayMemberSessionDto;
import org.itboys.mobile.entity.mongo.ZhongBaoChat;
import org.itboys.mobile.entity.mongo.ZhongBaoChatGroup;
import org.itboys.mobile.service.mongo.weixin.ZhongBaoWeiXinChatGroupService;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 作者：江雄
 * 时间：2017年5月9日
 * 描述：众包_微信_项目_controller
 */
@Controller
@RequestMapping("/zhongbao/weixin/chat")
public class ZhongBaoWeiXinChatController extends BaseController{
    @Autowired
    private ZhongBaoWeiXinChatGroupService chatGroupService;
    /**
     * 个人中心
     * @param request
     * @param response
     */
    @RequestMapping(value="/openByMemberId", method= RequestMethod.POST)
    @ApiOperation(value="[个人中心]打开聊天组，无论有没有都创建一个。创建后重新打开聊天组")
    public void openByMemberId(
            HttpServletRequest request,
            HttpServletResponse response,
            Model model,
            @ApiParam(required=true, name="memberId2", value="被聊天人ID")@RequestParam(value = "memberId2", required = true)Long memberId2
             ){
        try{
            SundayMemberSessionDto memberSessionDto = AccountIdHoldUtils.getSessionMember(request);
            String memberIds = memberSessionDto.getId()+","+memberId2;
            long groupId=  chatGroupService.generateGroup(memberSessionDto.getId(),memberId2,null,memberIds);
            ResponseMessage.success(groupId);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/zhongbao/weixin/chat/openByMemberId----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(CommonConstants.FAIL_CODE,msg);
        }
    }
    @RequestMapping(value="/openByGroupId", method= RequestMethod.GET)
    @ApiOperation(value="[项目或聊天组列表]打开聊天组，必须已知聊天租ID")
    public String openByGroupId(
            HttpServletRequest request,
            HttpServletResponse response,
            Model model,
            @ApiParam(required=true, name="groupId", value="聊天组ID")@RequestParam(value = "groupId", required = true)Long groupId
    ){
        try{
            SundayMemberSessionDto memberSessionDto = AccountIdHoldUtils.getSessionMember(request);
            ZhongBaoChatGroup group= chatGroupService.getById(groupId);
            model.addAttribute("group",group);
           List<ZhongBaoChat> chats = chatGroupService.open(memberSessionDto.getId(),groupId);
            //获取聊天记录
            model.addAttribute("chats",chats);
            //SundayMember member = memberService.getById(AccountIdHoldUtils.getSessionMember(request).getId());
            //  model.addAttribute("memberDto",member);
            return "/zhongbao/weixin/chat/index";
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/zhongbao/weixin/chat/openByGroupId----e="+e.getMessage());
            }
            e.printStackTrace();
            return "/zhongbao/weixin/error";
        }
    }
    /**
     * 新增项目
     * @param request
     * @param response
     * @param
     */
    @RequestMapping(value="/chat", method=RequestMethod.POST)
    @ApiOperation(value="【聊天】发布聊天内容")
    public void chat(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(required=true, name="groupId", value="聊天租ID")@RequestParam(value = "groupId", required = true)Long groupId,
            @ApiParam(required=true, name="content", value="内容或图片地址")@RequestParam(value = "content", required = true)String content

    ){
        try {
            SundayMemberSessionDto memberSessionDto = AccountIdHoldUtils.getSessionMember(request);
            chatGroupService.chat(memberSessionDto.getId(),groupId,content);
            ResponseMessage.success();
        } catch (Exception e) {

            String msg ="";
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
            }else{
                msg= CommonConstants.ERROMSG;
                logger.info("/zhongbao/weixin/chat/chat--------"+e);
            }
            e.printStackTrace();
            ResponseMessage.error(CommonConstants.FAIL_CODE,msg);
        }
    }

}
